//
//  addbaojiaViewController.m
//  HAODE
//
//  Created by panquanReabam.com on 15/9/18.
//  Copyright (c) 2015年 reabam.com. All rights reserved.
//
#import "MediaPromotionAddViewController.h"
#import "HttpRequest.h"
#import "RDVTabBarController.h"
#import "UIViewExt.h"
#import "ZJSwitch.h"
#import "AddCustomCell.h"
#import "VPImageCropperViewController.h"
#import "UpYun.h"
#import "inputHelper.h"
#import "TheLoginViewController.h"
#import "PulishPreviewModel.h"
#import "PublishPreviewViewController.h"

@interface MediaPromotionAddViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIActionSheetDelegate, UICollectionViewDelegateFlowLayout,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIGestureRecognizerDelegate,UITextFieldDelegate,UITextViewDelegate,VPImageCropperDelegate,UIImagePickerControllerDelegate>

@property(nonatomic,strong)NSString*imageSat;

@property(nonatomic,strong)NSString*imageUrl;
@end
@implementation MediaPromotionAddViewController
{
    UITextField *titleTextFied;
    UIView*heardView;
    UIView*myToolBar;
    NSMutableArray *contentName;
    NSMutableArray *imageArray;
    NSMutableArray*imageList;
    UIButton*coverimageView;
    UITextView*contentTv;
    UIImageView*imagess;
    UILabel*label;
    UIImageView*im;
    UILabel*l;
    UIView* guigeview;
    UIButton* tianjiashanping1;
    int i;
    UIButton*singleFingerOne;
    
}

@synthesize alt = alt;
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
    
}
-(void)BackAction:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.delegate = self;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [[self rdv_tabBarController] setTabBarHidden:YES];
    [self.navigationController.navigationBar setHidden:YES];
    [self setAutolayout];
    imageList=[[NSMutableArray alloc]init];
    [_backBtn addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    [_previewBtn addTarget:self action:@selector(baocun:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)baocunxia{
//    NSLog(@"-----------%@",imageList);
//     NSLog(@"-----------%@",contentName);
    NSMutableArray*items=[[NSMutableArray alloc]init];
    for (int j=0; j<imageList.count; j++) {
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSString *imageUrlStr = [imageList objectAtIndex:j];
        NSString *contentNameSte = [contentName objectAtIndex:j];
        [dic setValue:imageUrlStr forKey:@"imageUrl"];
        [dic setValue:contentNameSte forKey:@"content"];
        
        [items addObject:dic];
    }
    //  NSLog(@"-----------%@",items);
   
    //titleTextFied.text
    //self.imageUrl;
    //contentTv.text;
    
    PublishPreviewViewController *publishVC=[[PublishPreviewViewController alloc] init];
    publishVC.items=[items mutableCopy];
    publishVC.titleStr=titleTextFied.text;
    publishVC.contentStr=contentTv.text;
    publishVC.coverURLStr=self.imageUrl;
    [self.navigationController pushViewController:publishVC animated:YES];

    

}
-(void)baocun:(UIButton*)sender{
    {
       
        if ([titleTextFied.text length] <1)
        {
            [self showAlertMessage:@"请输入标题"];
        }
        else if(self.imageUrl.length<1 ){
        
            [self showAlertMessage:@"请选择封面"];
        
        }else
        
        
        {
            
            
             NSLog(@"-----------%@",imageArray);
            if (imageArray.count>0) {
                [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
                for (int j=0; j<imageArray.count;j++) {
                    
                    UIImage *portraitImg = [[UIImage alloc]init];
                    portraitImg = [self imageCompress:imageArray[j]];
                    UpYun *uy = [[UpYun alloc] init];
                    uy.successBlocker = ^(id data)
                    {
                      
                        NSString *imageURL;
                        imageURL=[data objectForKey:@"url"];
                        [imageList addObject:imageURL];
                        if (imageList.count==imageArray.count) {
                            
                            [Global hideProgressHUDInternal:self.view];
                            [self  baocunxia];
                        }
                        
                    };
                    uy.failBlocker = ^(NSError * error)
                    {
                        [Global hideProgressHUDInternal:self.view];
                        
                        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"上传失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                        [alert show];
                        NSLog(@"%@",error);
                    };
                    uy.progressBlocker = ^(CGFloat percent, long long requestDidSendBytes)
                    {
                     
                        [Global hideProgressHUDInternal:self.view];
                    };
                    
                    [uy uploadFile:portraitImg saveKey:[self getSaveKey]];
                    
                }

            }else{
            
            [self  baocunxia];
            
            }
        }
    }
    
    
}
-(void)uploadType{
NSUserDefaults *user11 = [NSUserDefaults standardUserDefaults];
NSString* Token11 = [user11 objectForKey:@"tokenId"];
NSMutableDictionary *params11 = [NSMutableDictionary new];
[params11 setValue:Token11 forKey:@"tokenId"];
[params11 setValue:@"product" forKey:@"uploadType"];

[Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
[HttpRequest requestData:@"Common/GetUpyunFormParams" params:params11 success:^(BOOL isSuccess, SeverData *severDataDict) {
    if (isSuccess) {
        if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
            [Global hideProgressHUDInternal:self.view];
           // NSLog(@"%@",severDataDict.dataDict);
            
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            NSString*policy=[severDataDict.dataDict objectForKey:@"policy"];
            NSString*signature=[severDataDict.dataDict objectForKey:@"signature"];
            NSString*action=[severDataDict.dataDict objectForKey:@"action"];
            [user setObject:signature forKey:@"signature"];
            [user setObject:policy forKey:@"policy"];
            [user setObject:action forKey:@"action"];
            [user synchronize];
            
        }else{
            [Global hideProgressHUDInternal:self.view];
            NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
            [Global showTextHudSub:requestResultStr view:self.view];
        }
        
    }
    else
    {
        [Global hideProgressHUDInternal:self.view];
        
        [Global showTextHudSub:severDataDict.resultStr view:self.view];
    }
    
}];
}
-(void)viewDidLoad{
    
    [super viewDidLoad];
    [self uploadType];
    
    _table.separatorStyle=UITableViewCellSeparatorStyleNone;
    contentName=[[NSMutableArray alloc]init];
    imageArray=[[NSMutableArray alloc]init];
    imageList=[[NSMutableArray alloc]init];
    self.title = @"自定义内容";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     backColor,
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    
    
    heardView = [[UIView alloc] initWithFrame:CGRectMake(0,0, ScreenWidth, 370)];
    [heardView setBackgroundColor: zuiqianhuiColor];
    myToolBar=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, viewheight)];
    myToolBar.backgroundColor=jianpancolor;
    // 手势
   
    UIButton*  tubtnDone=[[UIButton alloc]initWithFrame:CGRectMake(logoX,logoY, logoheight, logowidth)];
    [tubtnDone setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [tubtnDone addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:tubtnDone];
    UIButton*btnDone111=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width - 55, 12, 40, 16)];
    [btnDone111 setTitle:@"确定" forState:UIControlStateNormal];
    [btnDone111 setTitleColor:jianpancolor1 forState:UIControlStateNormal];
    btnDone111 .titleLabel .font=[UIFont systemFontOfSize:16];
    [btnDone111 addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:btnDone111];
    myToolBar.alpha=alp;
    UIButton* dabtn=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width-60, 0, 60, 40)];
    [dabtn addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:dabtn];
    _table.tableHeaderView=heardView;
    UIView*titleView=[[UIView alloc]initWithFrame:CGRectMake(0, 10, ScreenWidth, 45)];
    titleView.backgroundColor=[UIColor whiteColor];
    titleView.layer.borderWidth = 0.40;
    titleView.layer.borderColor = qianhuiColor.CGColor;
    [heardView addSubview:titleView];
    
    UILabel* title=[[UILabel alloc]initWithFrame:CGRectMake(15, 10, 55,45)];
    title.text=[NSString stringWithFormat:@"%@", @"*标题"];
    title.font=[UIFont systemFontOfSize:15];
    title.textColor=qianheiColor;
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@", @"*标题"]];

    
    [AttributedStr addAttribute:NSForegroundColorAttributeName
     
                          value:hongseColor
     
                          range:NSMakeRange(0, 1)];
    
    
    title.attributedText = AttributedStr;

    [heardView addSubview:title];
    
    titleTextFied=[[UITextField alloc]initWithFrame:CGRectMake(title.right,  10, ScreenWidth-95,  45)];
    titleTextFied.borderStyle = UITextBorderStyleNone;
    titleTextFied.font = [UIFont systemFontOfSize: 15];
    titleTextFied.textColor=qianheiColor;
    titleTextFied.autocapitalizationType = UITextAutocapitalizationTypeSentences;
    titleTextFied.tag=2;
    titleTextFied.placeholder = @"请输入标题"; //默认显示的字
    titleTextFied.delegate = self;
    [titleTextFied setUserInteractionEnabled:YES];
    titleTextFied.clearButtonMode = UITextFieldViewModeWhileEditing;
    [heardView addSubview:titleTextFied];
    titleTextFied.inputAccessoryView = myToolBar;
    
    UIView*coverView=[[UIView alloc]initWithFrame:CGRectMake(0, titleView.bottom+10, ScreenWidth, 145)];
    coverView.backgroundColor=[UIColor whiteColor];
    coverView.layer.borderWidth = 0.40;
    coverView.layer.borderColor = qianhuiColor.CGColor;
    [heardView addSubview:coverView];
    UILabel* cover=[[UILabel alloc]initWithFrame:CGRectMake(15, 0, 70,45)];
    cover.text=[NSString stringWithFormat:@"%@", @"*封面"];
    cover.font=[UIFont systemFontOfSize:15];
    cover.textColor=qianheiColor;
    NSMutableAttributedString *AttributedStr1 = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@", @"*封面"]];
    
    
    [AttributedStr1 addAttribute:NSForegroundColorAttributeName
     
                          value:hongseColor
     
                          range:NSMakeRange(0, 1)];
    
    
    cover.attributedText = AttributedStr1;

    [coverView addSubview:cover];
    coverimageView = [[UIButton alloc]initWithFrame:CGRectMake(20, cover.bottom+2, 180/2, 180/2)];
    coverimageView.layer.masksToBounds = YES;
    [coverimageView setImageWithURL:[NSURL URLWithString:@""] placeholderImage:[UIImage imageNamed:@"tianjiatupian"]];
    [coverimageView addTarget:self action:@selector(coverimageView:) forControlEvents:UIControlEventTouchUpInside];
    coverimageView.contentMode = UIViewContentModeScaleAspectFit;
    [coverView addSubview:coverimageView];

    UIView*contentView=[[UIView alloc]initWithFrame:CGRectMake(0, coverView.bottom+10, ScreenWidth, 140)];
    contentView.backgroundColor=[UIColor whiteColor];
    contentView.layer.borderWidth = 0.40;
    contentView.layer.borderColor = qianhuiColor.CGColor;
    [heardView addSubview:contentView];
    
    UILabel* content=[[UILabel alloc]initWithFrame:CGRectMake(15, 0, 70,40)];
    content.text=[NSString stringWithFormat:@"%@", @"推广说明"];
    content.font=[UIFont systemFontOfSize:15];
    content.textColor=qianheiColor;
    [contentView addSubview:content];
    contentTv=[[UITextView alloc]init];
    contentTv.frame=CGRectMake(15, content.bottom, ScreenWidth-40, 90);
    contentTv.backgroundColor = [UIColor whiteColor];//设置它的背景颜色/Users/jiezsoft/Desktop/
    contentTv.scrollEnabled = YES;//是否可以拖动
    contentTv.delegate=self;
    contentTv.tag=0;
    contentTv.font = [UIFont fontWithName:@"Arial" size:15.0];//设置字体名字和字体大小
    contentTv.layer.borderWidth =0;
    CGColorSpaceRef registedSpace11 = CGColorSpaceCreateDeviceRGB();
    CGColorRef tureBTncolorref111 = CGColorCreate(registedSpace11,(CGFloat[]){ 0, 0, 0, 0.3 });
    //tv.keyboardType = UIKeyboardTypePhonePad;
    [contentTv.layer setBorderColor:tureBTncolorref111];//边框颜色
    contentTv.layer.cornerRadius =0;
    [contentView addSubview:contentTv];
    l=[[UILabel alloc]init];
    l.frame =CGRectMake(23, 10, ScreenWidth-60, 15);
    l.text = @"请输入推广说明";
    l.textColor= [UIColor colorWithRed:204/255.0 green:204/255.0 blue:204/255.0 alpha:1];
    l.numberOfLines=0;
    l.font=[UIFont systemFontOfSize:14];
    l.backgroundColor = [UIColor clearColor];
    [contentTv addSubview:l];
    im=[[UIImageView alloc]initWithFrame:CGRectMake(0, 10, 18, 16)];
    im.image=[UIImage imageNamed:@"_0000_xingxifankui.png"];
    [contentTv addSubview:im];
    contentTv.inputAccessoryView = myToolBar;
    UIView*gayView=[[UIView alloc]initWithFrame:CGRectMake(0, 360, ScreenWidth, 10)];
    gayView.backgroundColor=zuiqianhuiColor;
    [heardView addSubview:gayView];
    [self foot];
    [_table reloadData];
}

-(void)adds:(UIButton*)sender{
    [contentName addObject:[NSString stringWithFormat:@"%@",  @""]];
    [imageArray addObject:[NSString stringWithFormat:@"%@",  @"123"]];
    [guigeview removeFromSuperview];
    guigeview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth,300)];
    guigeview.backgroundColor=zuiqianhuiColor;
    _table.tableFooterView=guigeview;
    [_table reloadData];
}
-(void)add:(UIButton*)sender{
   UIButton* button=(UIButton * )sender;
    AddCustomCell* cell=(AddCustomCell* )button.superview.superview;
    cell.shuzi= cell.shuzi;
    if ([cell.text.text length]>0) {
        [contentName addObject:[NSString stringWithFormat:@"%@",  @""]];
        [imageArray addObject:[NSString stringWithFormat:@"%@",  @"123"]];
        }else{
        [self showAlertMessage:@"请选填上面的内容"];
    }
    [_table reloadData];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [contentName count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    AddCustomCell* cell = (AddCustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"AddCustomCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
   
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.shanchu addTarget:self action:@selector(shanchu:) forControlEvents:UIControlEventTouchUpInside];
    cell.shanchu.tag=indexPath.row;
    cell.shuzi=[NSString stringWithFormat:@"%ld" ,indexPath.row];
    
    
    if ([[NSString stringWithFormat:@"%@",contentName[indexPath.row]]isEqualToString:@""]){
        label=[[UILabel alloc]init];
        label.frame =CGRectMake(23, 10, ScreenWidth-60, 15);
        label.text = @"请输入推广内容";
        label.textColor= [UIColor colorWithRed:204/255.0 green:204/255.0 blue:204/255.0 alpha:1];
        label.numberOfLines=0;
        label.font=[UIFont systemFontOfSize:14];

        label.backgroundColor = [UIColor clearColor];
        [cell.text addSubview:label];
        imagess=[[UIImageView alloc]initWithFrame:CGRectMake(0, 10, 18, 16)];
        imagess.image=[UIImage imageNamed:@"_0000_xingxifankui.png"];
        [cell.text addSubview:imagess];
    
       }else{
   
    
    
    }
    cell.text.text=contentName[indexPath.row];
    cell.text.delegate=self;
    cell.text.tag=1;
    UIView*gayView=[[UIView alloc]initWithFrame:CGRectMake(ScreenWidth-20, 0, 20, 300)];
    gayView.backgroundColor=zuiqianhuiColor;
    [cell.contentView addSubview:gayView];
    UIView*gayView1=[[UIView alloc]initWithFrame:CGRectMake(0, 290, ScreenWidth, 10)];
    gayView1.backgroundColor=zuiqianhuiColor;
    [cell.contentView addSubview:gayView1];
    
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth-20, 0.45)];
    lineLabel.backgroundColor=qianhuiColor;
    [cell.contentView addSubview:lineLabel];
    UILabel *lineLabel1=[[UILabel alloc] initWithFrame:CGRectMake(15, 140-0.45, ScreenWidth-70, 0.45)];
    lineLabel1.backgroundColor=qianhuiColor;
    [cell.contentView addSubview:lineLabel1];
    UILabel *lineLabel2=[[UILabel alloc] initWithFrame:CGRectMake(0, 290, ScreenWidth-20, 0.45)];
    lineLabel2.backgroundColor=qianhuiColor;
    [cell.contentView addSubview:lineLabel2];
    UILabel *lineLabel3=[[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth-19.55, 0, 290, 0.45)];
    lineLabel3.backgroundColor=qianhuiColor;
    [cell.contentView addSubview:lineLabel3];

    UIButton*deleteBtn=[[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-35, 125, 30, 30)];
    [deleteBtn setImage:[UIImage imageNamed:@"shanchu"] forState:UIControlStateNormal];
    [deleteBtn addTarget:self action:@selector(shanchu:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:deleteBtn];

if ([[NSString stringWithFormat:@"%@", imageArray[indexPath.row]]isEqualToString:@"123"]) {
   }else{
    
       [cell.imageUrlBtn setBackgroundImage:[imageArray objectAtIndex:indexPath.row] forState:UIControlStateNormal];
}
    cell.imageUrlBtn.tag=indexPath.row;

     [cell.imageUrlBtn addTarget:self action:@selector(imageUrlBtn:) forControlEvents:UIControlEventTouchUpInside];
    if (contentName.count ==indexPath.row+1) {
        UIButton* tianjiashanping=[[UIButton alloc]initWithFrame:CGRectMake(0, 300, ScreenWidth,45)];
        [tianjiashanping setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
        [tianjiashanping addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
        tianjiashanping.backgroundColor=[UIColor whiteColor];
        tianjiashanping.layer.borderWidth = 0.40;
        tianjiashanping.layer.borderColor = qianhuiColor.CGColor;
       UILabel* contentNameLabel=[[UILabel alloc]initWithFrame:CGRectMake(15, 0, ScreenWidth,45)];
        contentNameLabel.text=[NSString stringWithFormat:@"%@", @"＋  添加推广内容"];
        contentNameLabel.font=[UIFont systemFontOfSize:15];
        contentNameLabel.textColor=shenhuiColor;
        NSMutableAttributedString *AttributedStr1 = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@", @"＋  添加推广内容"]];
        [AttributedStr1 addAttribute:NSFontAttributeName
         
                               value:[UIFont systemFontOfSize:16]
         
                               range:NSMakeRange(0, 1)];
        
        [AttributedStr1 addAttribute:NSForegroundColorAttributeName
         
                               value:hongseColor
         
                               range:NSMakeRange(0, 1)];
        
        
        contentNameLabel.attributedText = AttributedStr1;
        [tianjiashanping addSubview:contentNameLabel];
        [cell.contentView addSubview:tianjiashanping];
    }
    
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (contentName.count ==indexPath.row+1) {
        return  345;
        }
    return  300;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}
//从指定索引移除

-(void)shanchu:(UIButton*)sender{
    [contentTv resignFirstResponder];
    [titleTextFied resignFirstResponder];
    UIButton* button=(UIButton * )sender;
    AddCustomCell* cell=(AddCustomCell* )button.superview.superview;
    cell.shuzi= cell.shuzi;
    [cell.text resignFirstResponder];
    [contentName removeObjectAtIndex:sender.tag];//从指定索引移除
    [imageArray removeObjectAtIndex:sender.tag];//从指定索引移除
    if (contentName.count==0) {
        [self foot];
        
    }
    
    [_table reloadData];
}

-(void)foot{
    [guigeview removeFromSuperview];
    guigeview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth,300)];
    guigeview.backgroundColor=zuiqianhuiColor;
    _table.tableFooterView=guigeview;
    tianjiashanping1=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth,45)];
    [tianjiashanping1 addTarget:self action:@selector(adds:) forControlEvents:UIControlEventTouchUpInside];
    tianjiashanping1.layer.borderWidth = 0.40;
    tianjiashanping1.layer.borderColor = qianhuiColor.CGColor;
    tianjiashanping1.backgroundColor=[UIColor whiteColor];
    UILabel* contentNameLabel=[[UILabel alloc]initWithFrame:CGRectMake(15, 0, ScreenWidth,45)];
    contentNameLabel.text=[NSString stringWithFormat:@"%@", @"＋  添加推广内容"];
    contentNameLabel.font=[UIFont systemFontOfSize:15];
    contentNameLabel.textColor=shenhuiColor;
    NSMutableAttributedString *AttributedStr1 = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@", @"＋  添加推广内容"]];
    [AttributedStr1 addAttribute:NSFontAttributeName
     
                           value:[UIFont systemFontOfSize:16]
     
                           range:NSMakeRange(0, 1)];
    
    [AttributedStr1 addAttribute:NSForegroundColorAttributeName
     
                           value:hongseColor
     
                           range:NSMakeRange(0, 1)];
    
    
    contentNameLabel.attributedText = AttributedStr1;
    [tianjiashanping1 addSubview:contentNameLabel];

    [guigeview addSubview:tianjiashanping1];

}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
   
    if (textView.tag==0) {
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        _table .frame =CGRectMake(0, -200, ScreenWidth, ScreenHeight);
        [UIView commitAnimations];
    }
    if (textView.tag==1) {
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        _table .frame =CGRectMake(0, -100, ScreenWidth, ScreenHeight);
        [UIView commitAnimations];
        AddCustomCell* cell=(AddCustomCell* )textView.superview;
        singleFingerOne=[[UIButton alloc]initWithFrame:self.view.frame];
        singleFingerOne.backgroundColor=[UIColor clearColor];
        [singleFingerOne addTarget:self action:@selector(closeKeyBoad:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:singleFingerOne];
       
    
    }
   return self;
}
- (void)textViewDidEndEditing:(UITextView *)textView{
    if (textView.tag==0) {
        
    }
    if (textView.tag==1) {
    AddCustomCell *cell  = (AddCustomCell *)[[textView superview] superview];
    NSIndexPath *indexPath = [_table indexPathForCell:cell];
    [contentName replaceObjectAtIndex:indexPath.row withObject:cell.text.text];
    }
}
-(void)textViewDidChange:(UITextView *)textView
{
 
    if (textView.tag==0) {
        if (contentTv.text.length == 0) {
        [im removeFromSuperview];
        im=[[UIImageView alloc]initWithFrame:CGRectMake(0, 10,18, 16)];
        im.image=[UIImage imageNamed:@"_0000_xingxifankui.png"];
        [contentTv addSubview:im];
        l.text = @"请输入推广说明";
        
    }else{
        [im removeFromSuperview];
        l.text = @"";
    }
 }
 
if (textView.tag==1) {
     
     if (textView.text.length == 0) {
         [imagess removeFromSuperview];
         
         imagess=[[UIImageView alloc]initWithFrame:CGRectMake(0, 10,18, 16)];
         imagess.image=[UIImage imageNamed:@"_0000_xingxifankui.png"];
         [textView addSubview:imagess];
         label.text = @"请输入推广内容";
         
     }else{
         [imagess removeFromSuperview];
         label.text = @"";
     }

}
}

- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark portraitImageView getter
#define ORIGINAL_MAX_WIDTH 640


- (void)imageUrlBtn:(UIButton*)sender {
    [contentTv resignFirstResponder];
    [titleTextFied resignFirstResponder];
    i=sender.tag;
   self.imageSat=@"imageUrlBtn";
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.view];
}
- (void)coverimageView:(UIButton*)sender {
    [contentTv resignFirstResponder];
    [titleTextFied resignFirstResponder];
     self.imageSat=@"coverimageView";
    
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.view];
}


#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            controller.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
        
    } else if (buttonIndex == 1) {
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
      portraitImg = [self imageCompress:portraitImg];
        if ([self.imageSat isEqualToString:@"imageUrlBtn"]) {
           [imageArray replaceObjectAtIndex:i withObject:portraitImg];
            NSLog(@"---%@",imageArray);
            [_table reloadData];
            
        }else{
            [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
            
            UpYun *uy = [[UpYun alloc] init];
                uy.successBlocker = ^(id data)
                {
                    
                    [Global hideProgressHUDInternal:self.view];
                    [coverimageView setImage:portraitImg forState:UIControlStateNormal];
                    self.imageUrl=[data objectForKey:@"url"];
                };
                uy.failBlocker = ^(NSError * error)
                {
                    [Global hideProgressHUDInternal:self.view];
                    
                    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"上传失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [alert show];
                    NSLog(@"%@",error);
                };
                uy.progressBlocker = ^(CGFloat percent, long long requestDidSendBytes)
                {
                    
                };
                
                [uy uploadFile:portraitImg saveKey:[self getSaveKey]];
                
        }
        [picker dismissViewControllerAnimated:YES completion:nil];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

-(void)closeKeyBoad:(UIButton*)sender{
    UIButton* button=(UIButton * )sender;
    AddCustomCell* cell=(AddCustomCell* )button.superview.superview;
    [cell.text resignFirstResponder];
    [singleFingerOne removeFromSuperview];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    _table .frame =CGRectMake(0, 44, ScreenWidth, ScreenHeight);
    [UIView commitAnimations];
}
-(void)OnTapDone{
   
    [contentTv resignFirstResponder];
    [titleTextFied resignFirstResponder];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    _table .frame =CGRectMake(0, 44, ScreenWidth, ScreenHeight);
    [UIView commitAnimations];
   
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}

#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return nil;
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}


-(void)idname{
    
    
    UIActionSheet *ac = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"用户相册", nil];
    [ac showInView:self.view];
    
}

-(NSString * )getSaveKey {

    NSDate *d = [NSDate date];
    return [NSString stringWithFormat:@"/%d/%d/%.0f.png",[self getYear:d],[self getMonth:d],[[NSDate date] timeIntervalSince1970]];
    
}

- (int)getYear:(NSDate *) date{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSYearCalendarUnit;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    int year=[comps year];
    return year;
}

- (int)getMonth:(NSDate *) date{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSMonthCalendarUnit;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    int month = [comps month];
    return month;
}
-(UIImage *)imageCompress:(UIImage *)image
{
    UIImage *comImage=image;
    NSData * sendImageData = UIImageJPEGRepresentation(comImage, 1.0);
    NSUInteger sizeOrigin = [sendImageData length];
    NSUInteger sizeOriginKB = sizeOrigin / 1024;
    
    if (sizeOriginKB >200) {
        float a = 80.0000;
        float b = (float)sizeOriginKB;
        float q = sqrtf(a / b);
        
        CGSize sizeImage = [comImage size];
        CGFloat widthSmall = sizeImage.width * q;
        CGFloat heighSmall = sizeImage.height * q;
        CGSize sizeImageSmall = CGSizeMake(widthSmall, heighSmall);
        
        UIGraphicsBeginImageContext(sizeImageSmall);
        CGRect smallImageRect = CGRectMake(0, 0, sizeImageSmall.width, sizeImageSmall.height);
        [image drawInRect:smallImageRect];
        UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        NSData *dataImage = UIImageJPEGRepresentation(smallImage, 1.0);
        sendImageData = dataImage;
       
        comImage= smallImage;
        // [_imageview1.image retain];
    }
    return comImage;
}
-(void)setAutolayout
{
    [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(self.view.mas_top);
        make.height.equalTo(@64);
    }];
    [_topLineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_topView.mas_left);
        make.right.equalTo(_topView.mas_right);
        make.bottom.equalTo(_topView.mas_bottom).with.offset(0);
        make.height.equalTo(@1);
    }];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_topView.mas_centerX);
        make.height.equalTo(@30);
        make.width.equalTo(@110);
        make.top.equalTo(_topView.mas_top).with.offset(25);
    }];
    
    [_backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_titleLabel.mas_centerY);
        make.height.equalTo(@30);
        make.width.equalTo(@60);
        make.left.equalTo(_topView.mas_left);
    }];
    [_previewBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_titleLabel.mas_centerY);
        make.height.equalTo(@30);
        make.width.equalTo(@60);
        make.right.equalTo(_topView.mas_right);
    }];
    [_table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(_topView.mas_bottom).with.offset(-20);
        make.bottom.equalTo(self.view.mas_bottom);
    }];

}
@end

